package com.roy.demo;

import com.zaxxer.hikari.HikariDataSource;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ShardingJdbcDemo {
    public static void main(String[] args) throws SQLException {
        // ======一、配置数据库
        Map<String, DataSource> dataSourceMap = new HashMap<>(2);
        //配置第一个数据源
        HikariDataSource dataSource0 = new HikariDataSource();
        dataSource0.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource0.setJdbcUrl("jdbc:mysql://localhost:3306/coursedb?serverTimeZone=GMT%2B8&userSSL=false");
        dataSource0.setUsername("root");
        dataSource0.setPassword("root");
        dataSourceMap.put("m2",dataSource0);
        //二、配置分库分表策略
        //配置分片规则
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
        //真实表分布
        TableRuleConfiguration courseTableConfig = new TableRuleConfiguration("course","m$->{1..2}.course_$->{1..2}");
        //主键策略
        courseTableConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE","cid",getProps()));
        Properties properties = new Properties();
        //打开日志输出
        properties.setProperty("sql.show","true");
        DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap,shardingRuleConfiguration,properties);
    }

    private static Properties getProps() {
         Properties props = new Properties();
         props.setProperty("worker.id","123");
         return props;
    }



    public void  querycourse(DataSource dataSource) throws SQLException{
        Connection conn = null;
        try{
            // sharding connection
            conn = dataSource.getConnection();
            // sharding statement
            Statement statement = conn.createStatement();
            String sql = "SELECT cid,cname,user_id,cstatus from course";
            // shardinig resultSet
            ResultSet result = statement.executeQuery(sql);
            while(result.next()){
                System.out.println("result:"+result.getInt("cid"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            if(null!=conn){
                conn.close();
            }
        }
    }
}
